'use strict';

const Service = require('egg').Service;

class CartService extends Service {

  // 新增
  async create(user_id, goods_id) {
    const { app } = this;
    const Op = app.Sequelize.Op;
    const res = await app.model.MallCart.findOne({
      // 根据user_id 和 doods_id同时查找，有没有记录
      where: { [Op.and]: [{ user_id, goods_id }] },
    });

    // 如果查到了 存在了一条记录 就让number+1
    if (res) {
      await res.increment('number');
      return await res.reload();
    }
    // 如果没有查找到就创建 添加一条记录
    return await app.model.MallCart.create({ user_id, goods_id });
  }


  // 获取列表
  async getList(payload) {
    const { app } = this;
    const { pageNum, pageSize } = payload;
    const { count, rows } = await app.model.MallCart.findAndCountAll({
      attributes: [ 'id', 'number', 'selected' ],
      order: [[ 'createdAt', 'desc' ]],
      include: {
        model: app.model.MallGoods,
        as: 'goods_info',
        attributes: [ 'id', 'goods_name', 'goods_price', 'goods_num', 'goods_desc', 'goods_img' ],
      },
      offset: (pageNum - 1) * pageSize,
      limit: pageSize * 1,
    });
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }

  // 删除
  async destroy(payload) {
    const { app } = this;
    return await app.model.MallCart.destroy({ where: { id: payload.ids } });
  }


  // 修改
  async update(payload) {
    const { app } = this;
    const { id, number, selected } = payload;
    const res = await app.model.MallCart.findByPk(id);
    if (!res) return '没查得到';

    number !== undefined ? (res.number = number) : '';

    if (selected !== undefined) {
      res.selected = selected;
    }
    return await res.save();
  }

  // 全选
  async selectAll(user_id) {
    const { app } = this;
    return await app.model.MallCart.update(
      { selected: true },
      { where: { user_id } }
    );
  }

  // 取消全选
  async unselectAll(user_id) {
    const { app } = this;
    return await app.model.MallCart.update({ selected: false }, { where: { user_id } });
  }

  // 获取购物车总数量
  async totalCarts() {
    const { app } = this;
    const { count } = await app.model.MallCart.findAndCountAll({});
    return {
      total: count,
    };
  }
}

module.exports = CartService;
